﻿using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour
{
	public float speed = 4f;
	public float jumpForce = 180f;
	public bool grounded = true;
	public Transform groundedEnd;
	public Vector2 spawnPoint = new Vector2(0f, 1f);

	float jumpTime, jumpDelay = 0.5f;
	bool jumped;

	Animator anim;

	void Start()
	{
		transform.position = spawnPoint;
		anim = GetComponent<Animator>();
	}

	void Update()
	{
		anim.ResetTrigger ("Shoot");
		Movement();
		Raycasting();
		Shooting();
	}

	void Raycasting()
	{
		Debug.DrawLine (this.transform.position, groundedEnd.position, Color.green);

		grounded = Physics2D.Linecast (this.transform.position, groundedEnd.position, 1 << LayerMask.NameToLayer ("Ground"));
	}

	void Movement()
	{
		anim.SetFloat ("speed", Mathf.Abs (Input.GetAxis ("Horizontal")));

		if (Input.GetAxisRaw("Horizontal") > 0) 
		{
			transform.Translate(Vector3.right * speed * Time.deltaTime);
			transform.eulerAngles = new Vector2(0,0);
		}

		if (Input.GetAxisRaw("Horizontal") < 0)
		{
			transform.Translate(Vector3.right * speed * Time.deltaTime);
			transform.eulerAngles = new Vector2(0,180);
		}

		if (Input.GetKeyDown (KeyCode.Space) && grounded == true)
		{
			rigidbody2D.AddForce(transform.up * jumpForce);
			jumpTime = jumpDelay;
			anim.SetTrigger("Jump");
			jumped = true;
		}

		jumpTime -= Time.deltaTime;

		if (jumpTime <= 0 && grounded && jumped)
		{
			anim.SetTrigger("Land");
			jumped = false;
		}
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if(other.CompareTag("DeadZone"))
		{
			Debug.Log ("Triggered");
			transform.position = spawnPoint;
		}
	}

	public void Shooting()
	{
		bool shoot = Input.GetButtonDown ("Fire1");
		shoot |= Input.GetButtonDown ("Fire2");

		if(shoot)
		{
			ProjectileScript weapon = GetComponent<ProjectileScript>();
			if(weapon)
			{
				weapon.Attack(false);
				anim.SetTrigger("Shoot");
			}
		}
	}
}
